package com.birdboot.core;

import com.birdboot.annotation.Controller;
import com.birdboot.annotation.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 使用当前类维护请求与对应的Controller方法的映射
 */
public class HandlerMapping {
    /**
     *  key:请求路径,比如:/regUser
     *  value:处理该请求的某Controller中的对应方法,比如UserController的reg方法对应的Method对象
     */
    private static Map<String, Method> mapping = new HashMap<>();

    static {
        initMapping();
    }

    /**
     * 扫描Controller初始化mapping
     */
    private static void initMapping(){
        try {
            File baseDir = new File(
                    HandlerMapping.class.getClassLoader().getResource(".").toURI()
            );
            File dir = new File(baseDir,"com/birdboot/controller");
            File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
            for(File sub : subs){
                String className = sub.getName().replace(".class","");
                Class cls = Class.forName("com.birdboot.controller."+className);
                //查看该类是否被注解@Controller标注
                if(cls.isAnnotationPresent(Controller.class)){
                    //扫描该类中所有方法
                    Method[] methods = cls.getDeclaredMethods();
                    for(Method method : methods){
                        //查看该方法是否被注解@RequestMapping标注
                        if(method.isAnnotationPresent(RequestMapping.class)){
                            RequestMapping rm = method.getAnnotation(RequestMapping.class);
                            //获取@RequestMapping参数值
                            String value = rm.value();
                            //将注解参数值(该方法处理的请求路径)以及该方法对象以key-value存入mapping
                            mapping.put(value,method);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据请求路径获取处理该请求的某个Controller中的对应方法
     * @param path
     * @return
     */
    public static Method getMethod(String path){
        return mapping.get(path);
    }

    public static void main(String[] args) {
        Method method = mapping.get("/regUser");
        System.out.println(method);
    }

}





